package com.lsp.base.utils.imageloader.transformation;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import com.blankj.utilcode.utils.ScreenUtils;
import com.blankj.utilcode.utils.SizeUtils;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

/**
 * 圆角
 *
 * @author com.lsp.ibxs
 * @created 17/1/20 15:04
 */
public class ImageTransformation extends BitmapTransformation {
  private int raduis;
  private Context mContext;

  public ImageTransformation(Context context) {
    super(context);
    raduis = SizeUtils.dp2px(4);
    this.mContext = context;
  }

  @Override
  protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
    int width = toTransform.getWidth();
    int height = toTransform.getHeight();

    Matrix matrix = new Matrix();
    float scaleWidth = ((float) width / ScreenUtils.getScreenWidth());
    float scaleHeight = scaleWidth;
    matrix.postScale(scaleWidth, scaleHeight);
    Bitmap newbmp = Bitmap.createBitmap(toTransform, 0, 0, width, height, matrix, true);

    //Bitmap bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888);
    //if (bitmap == null) {
    //  bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    //}
    //Canvas canvas = new Canvas(bitmap);
    //Paint paint = new Paint();
    //paint.setAntiAlias(true);
    //paint.setShader(new BitmapShader(toTransform, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    //
    //canvas.drawCircle(width > height ? height / 2 : height / 2,
    //    width > height ? height / 2 : height / 2, width > height ? height / 2 : width / 2, paint);
    return newbmp;
  }

  @Override public String getId() {
    return getClass().getName();
  }

  private Drawable zoomDrawable(Drawable drawable, int w, int h) {
    int width = drawable.getIntrinsicWidth();
    int height = drawable.getIntrinsicHeight();
    Bitmap oldbmp = drawableToBitmap(drawable);
    Matrix matrix = new Matrix();
    float scaleWidth = ((float) w / width);
    float scaleHeight = ((float) h / height);
    matrix.postScale(scaleWidth, scaleHeight);
    Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true);
    return new BitmapDrawable(null, newbmp);
  }

  private Bitmap drawableToBitmap(Drawable drawable) {
    int width = drawable.getIntrinsicWidth();
    int height = drawable.getIntrinsicHeight();
    Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
        : Bitmap.Config.RGB_565;
    Bitmap bitmap = Bitmap.createBitmap(width, height, config);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, width, height);
    drawable.draw(canvas);
    return bitmap;
  }
}
